#' @title 贝叶斯因子序贯分析图 #假设检验 #序贯分析
#' @description 展示贝叶斯因子随样本量增加的变化趋势，支持研究设计的样本量决策
#' @example
#' 使用示例：
#' set.seed(123)
#' df <- generate_sim_data()
#' bf_results <- calculate_sequential_BF(df, calculate_BF)
#' plot_bayes_factors(bf_results)

library(BayesFactor)
library(ggplot2)
library(dplyr)
set.seed(123)

# 生成模拟数据函数
generate_sim_data <- function(n=50) {
  data.frame(
    id = rep(1:n, each = 2),
    ismatch = rep(c("match", "mismatch"), n),
    rt = rnorm(2*n, mean = rep(c(500, 520), n), sd = 50)
  )
}

# 核心计算函数
calculate_BF <- function(df, dv="rt") {
  tmp_df <- tidyr::pivot_wider(df, id_cols = "id", 
                              names_from = "ismatch", 
                              values_from = dv)
  bf <- BayesFactor::ttestBF(tmp_df$match, tmp_df$mismatch, paired = TRUE)
  as.data.frame(bf)$bf
}

# 序贯分析框架
calculate_sequential_BF <- function(df, init_num = 2, step = 5) {
  ids <- unique(df$id)
  split_n <- unique(round(seq(init_num, length(ids), by = step)))
  
  lapply(split_n, function(n) {
    calculate_BF(df[df$id %in% sample(ids, n), ])
  }) |> setNames(split_n) |> 
    tibble::enframe(name = "n_subjects", value = "BF10") |> 
    tidyr::unnest(BF10) |> 
    dplyr::mutate(
      BF01 = 1/BF10,
      n_subjects = factor(n_subjects) |> as.numeric()
    ) 
}

# 可视化函数
plot_sequential_BF <- function(bf_data, thresholds = c(3, 10)) {
  ggplot2::ggplot(bf_data, aes(n_subjects)) +
    ggplot2::geom_line(aes(y = BF10, color = "BF10"), linewidth = 1.2) +
    ggplot2::geom_line(aes(y = BF01, color = "BF01"), linewidth = 1.2) +
    ggplot2::geom_hline(yintercept = thresholds, linetype = "dashed") +
    ggplot2::scale_color_manual(values = c("BF10" = "#E64B35", "BF01" = "#4DBBD5")) +
    ggplot2::labs(x = "样本量", y = "贝叶斯因子", 
                 title = "序贯贝叶斯因子分析") +
    ggplot2::theme_minimal(base_size = 13) +
    ggplot2::theme(legend.position = "top")
}

# 从简化的示例调用
df <- generate_sim_data(30)
bf_res <- calculate_sequential_BF(df)
plot_sequential_BF(bf_res)
